//
//  HLBaseCollectionCtl.m
//  s.
//
//  Created by fanshijian on 2022/8/24.
//  Copyright © 2022 J. All rights reserved.
//

#import "BaseCollectionViewController.h"
#import "KLCollectionBaseLayout.h"
#import <CALayer+YYAdd.h>
#import "BESimpleCollectionViewAdapter.h"
#import <LYEmptyView/LYEmptyViewHeader.h>
@interface BaseCollectionViewController ()

@property (assign, nonatomic) BOOL dloaded;
@property (assign, nonatomic,getter=isRefreshing) BOOL refreshing;

@end

@implementation BaseCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _collectionInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    self.view.backgroundColor = KLColor(self.containerColor);
    
    KLWKSelf
    self.emptyViewBlock = ^(MASConstraintMaker * _Nonnull make) {
        KLSTSelf
        kMakeEdgeV(self.collectionInsets);
    };
    
   
}

- (void)setCollectionInsets:(UIEdgeInsets)collectionInsets {
    _collectionInsets = collectionInsets;
    KLWKSelf
    self.emptyViewBlock = ^(MASConstraintMaker * _Nonnull make) {
        KLSTSelf
        kMakeEdgeV(self.collectionInsets);
    };
    
    [self collectionView];
}

- (void)setShowNoContent:(BOOL)showNoContent{
//    [super setShowNoContent:showNoContent];
    if (self.showNoContent) {
        if (_collectionView.mj_footer) {_collectionView.mj_footer = nil;}
    }else{
        if (_dataSources.count > 0 && self.can_pullup && !_collectionView.mj_footer){
            self.collectionView.mj_footer = [self.mj_footer_class footerWithRefreshingTarget:self refreshingAction:@selector(_more)];
            if ([self.collectionView.mj_footer isKindOfClass:MJRefreshBackNormalFooter.class]) {
                MJRefreshBackNormalFooter *header = (MJRefreshBackNormalFooter *)self.collectionView.mj_footer;
                header.stateLabel.textColor = KLColor(@"#999999");
                header.stateLabel.font = U_font(14);
            }
        }
    }
}
- (BOOL)jy_haveData {
    return self.dataSources.count!=0;
}
- (NSString *)containerColor{return @"#ffffff";}
- (NSString *)sectionColor{return @"#ffffff";}

- (Class)mj_footer_class{
    return MJRefreshBackNormalFooter.class;
}
- (Class)mj_header_class {
    return MJRefreshNormalHeader.class;
}

- (BOOL)sectionHeadersPinToVisibleBounds{return NO;}
- (BOOL)can_pulldown{
    return NO;
}
- (BOOL)can_pullup{
    return NO;
}

- (BOOL)show_allData {
    return NO;
}

- (void)setShowAllDataTip:(BOOL)showAllDataTip {
    
    if (_showAllDataTip == showAllDataTip) {
        return;
    }
    
    _showAllDataTip = showAllDataTip;
    if (showAllDataTip) {
        BaseModel * model = [[BaseModel alloc] init];
        model.idfBlock = ^NSString * _Nonnull{
            return @"BEBaseListFooterView";
        };
        model.layout.itemSize = CGSizeMake(kScreenWidth - self.collectionInsets.left - self.collectionInsets.right, 30);
        MainSectionModel * se = self.dataSources.lastObject;
        se.f_model = model;
    } else {
        MainSectionModel * se = self.dataSources.lastObject;
        se.f_model = nil;
    }
    [self reloadIfNeeded];
}

- (UICollectionView *)collectV {
    return self.collectionView;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        NSString *clsStr = nil;
        if (self.layoutStringBlock) {
            clsStr = self.layoutStringBlock();
        }
        KLCollectionBaseLayout *layout = nil;
        if (clsStr) {
            Class cls = NSClassFromString(clsStr);
            id myobjc = ((id (*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
            layout = ((id (*)(id, SEL))objc_msgSend)(myobjc, @selector(init));
        }else {
            layout = [[KLCollectionBaseLayout alloc] init];
        }
        
        layout.scrollDirection          = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing       = 0;
        layout.minimumInteritemSpacing  = 0;
        layout.sectionHeadersPinToVisibleBounds = self.sectionHeadersPinToVisibleBounds;
        UICollectionView *obj = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        
        obj.backgroundColor = UIColor.whiteColor;
        [self.view addSubview:_collectionView = obj];
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            if (self.collectionLayoutBlock) {
                self.collectionLayoutBlock(make);
                self.collectionLayoutBlock = nil;
            }else{
                kMakeEdgeV(self.collectionInsets);
            }
        }];
        if (self.can_pulldown) {
            obj.mj_header = [self.mj_header_class headerWithRefreshingTarget:self refreshingAction:@selector(_refresh)];
            obj.mj_header.backgroundColor = KLColor(self.containerColor);
            obj.mj_header.isCollectionViewAnimationBug = YES;
            if ([obj.mj_header isKindOfClass:[MJRefreshNormalHeader class]]) {
                MJRefreshNormalHeader *header = (MJRefreshNormalHeader *)obj.mj_header;
                header.stateLabel.textColor = KLColor(@"#999999");
                header.stateLabel.font = U_font(14);
                header.lastUpdatedTimeLabel.textColor = KLColor(@"#999999");
                header.lastUpdatedTimeLabel.font = U_font(14);
            }
        }
//        obj.backgroundColor                        = KLColor(self.containerColor);
        if (@available(iOS 11.0, *)) {
            obj.contentInsetAdjustmentBehavior     = UIScrollViewContentInsetAdjustmentNever;
        }
        obj.collectionViewAdapter = [BESimpleCollectionViewAdapter new];
        obj.collectionViewAdapter.controller = self;
        LYEmptyView * emptyView = [LYEmptyView emptyViewWithImage:U_imageNamed(self.empty_image) titleStr:nil detailStr:nil];
        emptyView.contentViewY = 100;
        _collectionView.ly_emptyView = emptyView;
    }
    return _collectionView;
}

- (void)_refresh{
    _refreshing = YES;
    [self refreshRequest];
}
/** 加载更多  */
- (void)_more{
    [self loadMore];
}

/** 刷新  */
- (void)setDataSources:(NSArray<MainSectionModel *> *)dataSources {
    if (_dataSources != dataSources) {
        if (!_dataSources && dataSources.count == 0) {
            self.showNoContent = YES;
            self.showAllDataTip = NO;
        }else{
            if (!_dataSources) {[self.view.layer addFadeAnimationWithDuration:0.25 curve:(UIViewAnimationCurveEaseIn)];}
            _dataSources = dataSources;
            self.showNoContent = (dataSources.count == 0);
            _dloaded     = YES;
        }
        [self reloadIfNeeded];
    }else if (!_dataSources && !dataSources){//初始数据为空
        self.showNoContent = (_dataSources.count == 0);
        [self reloadIfNeeded];
    }
}

- (void)_handleMore:(NSArray *)dataSources section:(MainSectionModel *)ms {
    BOOL reduce = NO;
    if (_dataSources.count > 0) {
        if ((!dataSources || dataSources.count == 0) && !ms.modified) {//没有更多数据
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            return;
        }
        if (ms) {//部分section刷新, 如果ms依然有，直接刷新
            if(dataSources.count) [ms.items addObjectsFromArray:dataSources];
        }else{
            NSMutableArray *ds = (id)_dataSources;
            if (![ds isKindOfClass:NSMutableArray.class] ) ds = [NSMutableArray arrayWithArray:_dataSources];
            if (ds.count > 100) {//>50 item remove 10 items from top
                [ds removeObjectsInRange:NSMakeRange(0, 10)];
                reduce = YES;
            }
            [ds addObjectsFromArray:dataSources];
            _dataSources = ds;
        }
    }else{
        if (!dataSources || dataSources.count == 0) {//没有更多数据
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            return;
        }else{
            _dataSources = dataSources.mutableCopy;
        }
    }
    if (ms && ms.idx) {
        [self _reloadSections:[NSIndexSet indexSetWithIndex:ms.idx.integerValue] reduced:reduce];
    }else{
        [self _reloadIfNeededReduced:reduce];
    }
}

- (void)reloadIfNeeded {
    [self _reloadIfNeededReduced:NO];
    if (self.refreshing) {
        [self _endRefresh];
    }
}

- (void)_resetFooterState{
    if (self.can_pullup && self.can_reset_footer && self.collectionView.mj_footer.state == MJRefreshStateNoMoreData) {
        [self.collectionView.mj_footer resetNoMoreData]; //恢复数据
    }
}

- (BOOL)can_reset_footer{
    return _dataSources.count == 0 || _dloaded;
}

- (void)_reloadIfNeededReduced:(BOOL)reduce{
    [self _resetFooterState];
    !self.show_allData ? : (self.showAllDataTip = _total <= _dataSources.count);
    if (reduce) [self _reduceScrollCollectionView];
    [UIView performWithoutAnimation:^{
        self.collectionView.collectionViewAdapter.keyPathOfSubData = @"items";
        self.collectionView.cellDatas = self.dataSources;
        self.collectionView.headerDatas = self.dataSources;
        self.collectionView.footerDatas = self.dataSources;
        [self.collectionView reloadData];
    }];
}

- (void)_reloadSections:(NSIndexSet *)indexSet reduced:(BOOL)reduce{
    [self _resetFooterState];
    if (reduce) [self _reduceScrollCollectionView];
    [self.collectionView reloadSections:indexSet];
}

- (void)_reduceScrollCollectionView{
    if (self.dataSources.count - 10 > 0) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:self.dataSources.count - 10] atScrollPosition:(UICollectionViewScrollPositionTop) animated:NO];
    }
}

- (void)_endRefresh{
    if (_collectionView.mj_header.isRefreshing) {
        [_collectionView.mj_header endRefreshing];
    }
    if (_collectionView.mj_footer.isRefreshing) {
        [_collectionView.mj_footer endRefreshing];
    }
    _refreshing = NO;
}

#pragma mark - 请求返回
- (void)finishRequestWithOperation:(AFHTTPRequestOperation *)operation data:(id)data vmsg:(NSString *)msg more:(BOOL)more {
    [super finishRequestWithOperation:operation data:data vmsg:msg more:more];
    BOOL isRefresh = self.isRefreshing;
    [self _endRefresh];
    if (!msg) {
        id dat = data[@"data"];
        if (!dat) {
            dat = data[@"rows"];
        }
        if (!dat) {
            dat = data[@"records"];
        }
        if ([dat respondsToSelector:@selector(count)] && [dat count] > 0) {
            [self transformMetaData:dat handle:(more && !isRefresh) ? ^(id _Nonnull list, MainSectionModel *ms) {
                [self _handleMore:list section:ms];
            } : NULL];
        }else{
            if (more) {
                if ([self can_pullup]) [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.dataSources = nil;
            }
        }
    }
}

- (void)transformMetaData:(NSDictionary *)data handle:(void (^)(id, MainSectionModel *))handle{}

@end
